<template>
  <div class="app-container">

    <el-card class="box-card">
      <h3>编辑</h3>
      <el-form ref="ioralRaw" :rules="rules" :model="ioralRaw" label-width="150px">
        <el-form-item label="生产单位" prop="productionAddress">
          <el-select v-model="ioralRaw.productionAddress" filterable clearable placeholder="请选择生产单位">
            <el-option
              v-for="item in productionAddresss"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="产品规格" prop="rawNumber1" >
          <el-input v-model="ioralRaw.specifications" placeholder="请输入规格"/>
        </el-form-item>-->
        <el-form-item label="出厂活度" prop="dispatchActivity">
          <el-input v-model="ioralRaw.dispatchActivity" placeholder="">
            <!--<template slot="append">元</template>-->
          </el-input>
        </el-form-item>

        <el-form-item label="标定活度" prop="calibrationActivity">
          <el-input v-model="ioralRaw.calibrationActivity" placeholder="">
            <!--<template slot="append">元</template>-->
          </el-input>
        </el-form-item>
        <el-form-item label="产品批号" prop="batchNumber">
          <el-input v-model="ioralRaw.batchNumber" placeholder="请输入产品批号">
            <!--<template slot="append">元</template>-->
          </el-input>
        </el-form-item>
        <el-form-item label="计量单位" prop="unit">
          <el-select v-model="ioralRaw.unit" placeholder="请选择计量单位">
            <el-option
              v-for="item in units"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="供应商" prop="supplier">
          <el-input v-model="ioralRaw.supplier" placeholder="请选择供应商">
            &lt;!&ndash;<template slot="append">元</template>&ndash;&gt;
          </el-input>
        </el-form-item>-->
        <el-form-item label="总活度" prop="count">
          <el-input v-model="ioralRaw.totalActivity" placeholder="请输入总活度">
            <!--<template slot="append">元</template>-->
          </el-input>
        </el-form-item>
        <el-form-item label="体积" prop="volume">
          <el-input v-model="ioralRaw.volume" placeholder="请输入体积">
            <!--<template slot="append">元</template>-->
          </el-input>
        </el-form-item>
        <el-form-item label="购进日期" prop="purchaseDate">
          <el-date-picker
            class="custom-width"
            v-model="ioralRaw.purchaseDate"
            type="date"
            placeholder="选择购进日期日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="件数" prop="pieces">
          <el-input v-model="ioralRaw.pieces"/>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="ioralRaw.notes"/>
        </el-form-item>

      </el-form>
    </el-card>

    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleEdit">更新</el-button>
    </div>
  </div>
</template>

<style>
.el-card {
  margin-bottom: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
// eslint-disable-next-line no-unused-vars
import { detailIoralRaw, editIoralRaw } from '@/api/business/ioralRaw'
import { createStorage, uploadPath } from '@/api/business/storage'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

export default {
  name: 'productProductionedit',
  components: { Editor },
  data() {
    return {
      uploadPath,
      newKeywordVisible: false,
      newKeyword: '',
      keywords: [],
      galleryFileList: [],
      productionAddresss:[{label:"波兰",value:"波兰"},{label: "南非",value: "南非"}],
      units:[{label:"GBq",value:"GBq"},{label:"Ci",value:"Ci"}],
      productProduction: {},
      ioralRaw:{},
      specVisiable: false,
      specForm: { specification: '', value: '', picUrl: '' },
      specifications: [{ specification: '规格', value: '标准', picUrl: '' }],
      mods: [
        { id: 0, specifications: ['标准'], price: 0.0, number: 0, url: '' }
      ],
      /* attributeVisiable: false,*/
      /* attributeForm: { attribute: '', value: '' },
      attributes: [],*/
      rules: {
        batchNumber: [
          { required: true, message: '产品批号不能为空', trigger: 'blur' }
        ],
        rawNumber1: [{ required: true, message: '原料批号不能为空', trigger: 'blur' }]
      },
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: [
          'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
        ],
        toolbar: [
          'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
          'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
        ],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData)
            .then(res => {
              success(res.data.data.url)
            })
            .catch(() => {
              failure('上传失败，请重新上传')
            })
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Dts-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init: function() {
      if (this.$route.query.id == null) {
        return
      }
      console.log("查询对应原料信息")

      const ioralRawId = this.$route.query.id
      detailIoralRaw(ioralRawId).then(response => {
        this.ioralRaw = response.data.data.ioralRaw
        /* this.specifications = response.data.data.specifications*/
        /* for (var i = 0; i < this.productProduction.gallery.length; i++) {
          this.galleryFileList.push({
            url: this.productProduction.gallery[i]
          })
        }*/
       /* const keywords = response.data.data.productProduction.keywords
        if (keywords !== null) {
          this.keywords = keywords.split(',')
        }*/
      })

      /* listCatAndBrand().then(response => {
        this.categoryList = response.data.data.categoryList
        this.brandList = response.data.data.brandList
      })*/
    },
    /* handleCategoryChange(value) {
      this.productProduction.categoryId = value[value.length - 1]
    },*/
    handleCancel: function() {
      this.$router.push({ path: '/productProduction/list' })
    },
    handleEdit: function() {
      const finalIoralRaw = {
        ioralRaw: this.ioralRaw

      }
      console.log(finalIoralRaw)
      editIoralRaw(finalIoralRaw)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '更新成功'
          })
          this.$router.push({ path: '/iorders/listRaw' })
        })
        .catch(response => {
          MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
            confirmButtonText: '确定',
            type: 'error'
          })
        })
    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1)
      this.productProduction.keywords = this.keywords.toString()
    },
    showInput() {
      this.newKeywordVisible = true
      this.$nextTick(_ => {
        this.$refs.newKeywordInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const newKeyword = this.newKeyword
      if (newKeyword) {
        this.keywords.push(newKeyword)
        this.productProduction.keywords = this.keywords.toString()
      }
      this.newKeywordVisible = false
      this.newKeyword = ''
    },
    uploadPicUrl: function(response) {
      this.productProduction.picUrl = response.data.url
    },
    uploadOverrun: function() {
      this.$message({
        type: 'error',
        message: '上传器材个数超出限制!最多上传5张图片!'
      })
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.productProduction.gallery.push(response.data.url)
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.productProduction.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.productProduction.gallery[i] === url) {
          this.productProduction.gallery.splice(i, 1)
        }
      }
    },
    specChanged: function(label) {
      if (label === false) {
        this.specifications = [
          { specification: '规格', value: '标准', picUrl: '' }
        ]
        this.products = [
          { id: 0, specifications: ['标准'], price: 0.0, number: 0, url: '' }
        ]
      } else {
        this.specifications = []
        this.products = []
      }
    },
    uploadSpecPicUrl: function(response) {
      this.specForm.picUrl = response.data.url
    },
    handleSpecificationShow() {
      this.specForm = { specification: '', value: '', picUrl: '' }
      this.specVisiable = true
    },
    handleSpecificationAdd() {
      var index = this.specifications.length - 1
      for (var i = 0; i < this.specifications.length; i++) {
        const v = this.specifications[i]
        if (v.specification === this.specForm.specification) {
          index = i
        }
      }

      this.specifications.splice(index + 1, 0, this.specForm)
      this.specVisiable = false

      this.specToProduct()
    },
    handleSpecificationDelete(row) {
      const index = this.specifications.indexOf(row)
      this.specifications.splice(index, 1)
      this.specToProduct()
    },
    specToProduct() {
      if (this.specifications.length === 0) {
        return
      }
      // 根据specifications创建临时规格列表
      var specValues = []
      var spec = this.specifications[0].specification
      var values = []
      values.push(0)

      for (var i = 1; i < this.specifications.length; i++) {
        const aspec = this.specifications[i].specification

        if (aspec === spec) {
          values.push(i)
        } else {
          specValues.push(values)
          spec = aspec
          values = []
          values.push(i)
        }
      }
      specValues.push(values)

      // 根据临时规格列表生产货品规格
      // 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
      var productsIndex = 0
      var products = []
      var combination = []
      var n = specValues.length
      for (var s = 0; s < n; s++) {
        combination[s] = 0
      }
      var index = 0
      var isContinue = false
      do {
        var specifications = []
        for (var x = 0; x < n; x++) {
          var z = specValues[x][combination[x]]
          specifications.push(this.specifications[z].value)
        }
        products[productsIndex] = {
          id: productsIndex,
          specifications: specifications,
          price: 0.0,
          number: 0,
          url: ''
        }
        productsIndex++

        index++
        combination[n - 1] = index
        for (var j = n - 1; j >= 0; j--) {
          if (combination[j] >= specValues[j].length) {
            combination[j] = 0
            index = 0
            if (j - 1 >= 0) {
              combination[j - 1] = combination[j - 1] + 1
            }
          }
        }
        isContinue = false
        for (var p = 0; p < n; p++) {
          if (combination[p] !== 0) {
            isContinue = true
          }
        }
      } while (isContinue)

      this.products = products
    },
    handleProductShow(row) {
      this.productForm = Object.assign({}, row)
      this.productVisiable = true
    },
    uploadProductUrl: function(response) {
      this.productForm.url = response.data.url
    },
    handleProductEdit() {
      for (var i = 0; i < this.products.length; i++) {
        const v = this.products[i]
        if (v.id === this.productForm.id) {
          this.products.splice(i, 1, this.productForm)
          break
        }
      }
      this.productVisiable = false
    },
    handleAttributeShow() {
      this.attributeForm = {}
      this.attributeVisiable = true
    },
    handleAttributeAdd() {
      this.attributes.unshift(this.attributeForm)
      this.attributeVisiable = false
    },
    handleAttributeDelete(row) {
      const index = this.attributes.indexOf(row)
      this.attributes.splice(index, 1)
    }
  }
}
</script>
